<?php

// lookup the most recent instance
$query = "SELECT id, state, days, style, start_node, stale_dn, track_id"
   		." FROM n_adc WHERE style LIKE 'stale' AND state != 3";
$result = db_query($query);
if(!$result) {
	echo "error: wasn't able to find list in the instance\n";
	exit(1);
}
// loop through until we have the last instance
$instance = mysql_fetch_assoc($result);
while($next = mysql_fetch_assoc($result)) {
	$instance = $next;
}

// load up the exception needles
$query = "SELECT pattern, addedBy FROM n_adc_exceptions WHERE isActive=true";
$r_exceptions = db_query($query);
if(!$r_exceptions) {
	echo "error: unable to access table 'exceptions'\n";
	exit(1);
}
$exceptions = array();
while($exception = mysql_fetch_assoc($r_exceptions)) {
	$exceptions[] = $exception;
}

// used to display who added the acception
function getExceptionAddedBy($exceptions, $netbios) {
	$isException = false;
	reset($exceptions);
	foreach($exceptions as $exception) {
		$pattern = $exception["pattern"];
		if(preg_match("/^".$pattern."\Z/i", $netbios)) {
			return $exception["addedBy"];
		}
	}

	return $false;
}

// display ad objects not pending deletion
$query = "SELECT * FROM n_adc_". $instance["id"] ." WHERE isIgnore=1 ORDER BY netbios ASC";
$result = db_query($query);
if(!$result) {
	echo "error: wasn't able to find list in the instance\n";
	exit(1);
}
?>

<script>
tables.push([
	"table_stale_activity",
	google.visualization.arrayToDataTable([
		['Machine Account', 'Reason', 'Requested By', 'Location']

<?php
while($next = mysql_fetch_assoc($result)) {
	$reason = "";
	if($next["byException"]) {
		$reason = "byException";
	}
	elseif($next["byLogon"]) {
		$reason = "byLogon";
	}
	elseif($next["byPing"]) {
		$reason = "byPing";
	}
	elseif($next["byEnable"]) {
		$reason = "byEnable";
	}
	elseif($next["byMove"]) {
		$reason = "byMove";
	}
	elseif($next["byDelete"]) {
		$reason = "byDelete";
	}

	// get simple formant of dn
	$tmpstr = "";
	$parts = explode(",", $next["dn_orig"]);
	$parts = array_reverse($parts);
	foreach($parts as $part) {
		$pieces = explode("=", $part);
		$tmpstr .= "/". $pieces[1];
	}
	$tmpstr = ltrim($tmpstr, "/");
//	echo "<td>$tmpstr\n";

	if(!strcmp($reason, "byException")) {
		$addedBy = getExceptionAddedBy($exceptions, $next["netbios"]);
	}
	else {
		$addedBy = "";
	}

	echo ",["
		."'". $next["netbios"] ."'"
		.",'".  $reason ."'"
		.",'".  $addedBy ."'"
		.",'".  $tmpstr ."'"
		."]\n";
}

?>
		])
	]);
</script>
